import React, { memo, useState } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { onAddSalaryItem, onEditSalaryItem } from '@/services/salaryManage/salaryCalculate';
import { COMMON_NAME } from '@/pages/SalaryManage/utils';
import styles from '../../index.less';

const AddSalaryItemModal = ({
    visible = false,
    onChange, onCancel,
    form,
    itemType = 'add',
    isEdit = false,
    editData = {},
    currentOrgCode
}) => {
    const { getFieldDecorator, validateFields } = form;
    const title = itemType === 'add' ? '薪资加项' : '薪资减项';
    const titleType = isEdit ? '编辑' : '新增';
    const [loading, setLoading] = useState(false);
    const onAdd = async values => {
        try {
            setLoading(true);
            const params = {
                organizationCode: currentOrgCode,
                itemType: itemType === 'add' ? 2 : 3,
                ...values
            };
            if (isEdit) {
                params.id = editData.parentId
            }
            const { code, msg } = isEdit
                ? await onEditSalaryItem(params)
                : await onAddSalaryItem(params);
            if (code === 10000) {
                onChange();
                message.success(`${titleType}成功！`);
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    };
    return <Modal
        title={`${titleType}${title}`}
        visible={visible}
        width={640}
        confirmLoading={loading}
        className={styles.formModal}
        onOk={() => {
            validateFields((err, values) => {
                console.log(values);
                if (!err) {
                    console.log('Received values of form: ', values);
                    onAdd(values);
                }
            });
        }}
        onCancel={onCancel}
        destroyOnClose
    >
        <Form>
            <Form.Item>
                {getFieldDecorator('parentName', {
                    initialValue: editData.parentName,
                    rules: [
                        { required: true, message: `请输入${title}` },
                        {
                            max: 20,
                            message: '不能超过20个字符'
                        },
                        {
                            pattern: COMMON_NAME.REG,
                            message: COMMON_NAME.MESSAGE
                        }
                    ]
                })(
                    <Input
                        placeholder={`请输入${title}`}
                        maxLength={20}
                    />
                )}
            </Form.Item>
        </Form>
    </Modal>
};
export default memo(Form.create({ name: 'addSalaryItemModal' })(AddSalaryItemModal))
